import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  Typography,
  Space,
  Button,
  Tag,
  Avatar,
  Divider,
  Spin,
  message,
  Row,
  Col,
  Select,
  Popconfirm
} from 'antd';
import {
  EyeOutlined,
  ArrowLeftOutlined,
  EditOutlined,
  CalendarOutlined,
  UserOutlined,
  FileOutlined
} from '@ant-design/icons';
import { getUser } from '../../utils';
import AttachmentPreview from '../../components/AttachmentPreview';
import PdfViewer from '../../components/PdfViewer/PdfViewer';
import './ArticleDetail.scss';

const { Title, Text } = Typography;

const ArticleDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [user] = useState(getUser());
  const [article, setArticle] = useState(null);
  const [loading, setLoading] = useState(true);
  const [statusLoading, setStatusLoading] = useState(false);

  useEffect(() => {
    if (id) {
      fetchArticle();
    }
  }, [id]);

  const fetchArticle = async () => {
    try {
      setLoading(true);
      const response = await fetch(`http://211.86.197.10:9091/api/articles/${id}`);
      const result = await response.json();

      if (result.success) {
        setArticle(result.data);
      } else {
        message.error('作品不存在或已被删除');
        navigate('/');
      }
    } catch (error) {
      console.error('获取作品详情错误:', error);
      message.error('获取作品详情失败');
      navigate('/');
    } finally {
      setLoading(false);
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  const handleEdit = () => {
    navigate(`/create?id=${id}`);
  };

  const handleStatusChange = async (newStatus) => {
    try {
      setStatusLoading(true);
      const token = localStorage.getItem('token');
      
      const response = await fetch(`http://211.86.197.10:9091/api/articles/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          ...article,
          status: newStatus
        })
      });

      const result = await response.json();

      if (result.success) {
        setArticle(prev => ({ ...prev, status: newStatus }));
        message.success(`作品状态已更新为${getStatusText(newStatus)}`);
      } else {
        message.error(result.message || '状态更新失败');
      }
    } catch (error) {
      console.error('状态更新错误:', error);
      message.error('状态更新失败');
    } finally {
      setStatusLoading(false);
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'draft': return '草稿';
      case 'published': return '已发布';
      case 'archived': return '已归档';
      default: return status;
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'draft': return 'orange';
      case 'published': return 'green';
      case 'archived': return 'gray';
      default: return 'default';
    }
  };

  if (loading) {
    return (
      <div className="article-detail-container" style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
        <div style={{ marginTop: 16 }}>加载中...</div>
      </div>
    );
  }

  if (!article) {
    return (
      <div className="article-detail-container" style={{ textAlign: 'center', padding: '100px 0' }}>
        <Text type="secondary">作品不存在</Text>
      </div>
    );
  }

  const isAuthor = user && user.id === article.user_id;

  return (
    <div className="article-detail-container">
      <Card>
        {/* 头部操作栏 */}
        <div className="article-header">
          <div className="header-left">
            <Button 
              icon={<ArrowLeftOutlined />} 
              onClick={handleBack}
              style={{ marginBottom: 16 }}
            >
              返回
            </Button>
            
            {isAuthor && (
              <Button 
                type="primary"
                icon={<EditOutlined />} 
                onClick={handleEdit}
                style={{ marginBottom: 16, marginLeft: 8 }}
              >
                编辑
              </Button>
            )}
          </div>
          
          {isAuthor && (
            <div className="header-right" style={{ marginBottom: 16 }}>
              <Space>
                <span>状态：</span>
                <Select
                  value={article.status}
                  onChange={handleStatusChange}
                  loading={statusLoading}
                  style={{ width: 120 }}
                  options={[
                    { value: 'draft', label: '草稿' },
                    { value: 'published', label: '已发布' },
                    { value: 'archived', label: '已归档' }
                  ]}
                />
              </Space>
            </div>
          )}
        </div>

        {/* 作品标题 */}
        <Title level={1} style={{ textAlign: 'center', marginBottom: 24 }}>
          {article.title}
        </Title>

        {/* 作品元信息 */}
        <Row justify="center" style={{ marginBottom: 32 }}>
          <Col>
            <Space size="large" wrap>
              <Space>
                <Avatar 
                  src={article.avatar_url} 
                  icon={<UserOutlined />}
                  size="small"
                />
                <Text>{article.username}</Text>
              </Space>
              
              <Space>
                <CalendarOutlined />
                <Text type="secondary">
                  {new Date(article.created_at).toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  })}
                </Text>
              </Space>

              <Tag color={getStatusColor(article.status)}>
                {getStatusText(article.status)}
              </Tag>
            </Space>
          </Col>
        </Row>

        {/* 封面图片 */}
        {article.cover_image && (
          <div style={{ textAlign: 'center', marginBottom: 32 }}>
            <img 
              src={article.cover_image} 
              alt="封面图片"
              style={{ 
                maxWidth: '100%', 
                maxHeight: '400px',
                borderRadius: '8px',
                boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
              }}
            />
          </div>
        )}

        {/* 作品内容 */}
        <div className="article-content">
          <div 
            dangerouslySetInnerHTML={{ __html: article.content_html }}
            style={{
              lineHeight: '1.8',
              fontSize: '16px',
              color: '#333'
            }}
          />
        </div>

        {/* 作品描述 */}
        {article.description && (
          <div style={{ marginBottom: 32 }}>
            <Title level={4}>作品描述</Title>
            <Typography.Paragraph style={{ fontSize: '16px', lineHeight: '1.6' }}>
              {article.description}
            </Typography.Paragraph>
            <Divider />
          </div>
        )}

        {/* 附件预览 - 优先显示PDF */}
        {article.attachments && article.attachments.length > 0 && (
          <div style={{ marginBottom: 32 }}>
            <Title level={4}>
              <FileOutlined style={{ marginRight: 8 }} />
              作品附件 ({article.attachments.length})
            </Title>
            <Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
              以下是作品的相关附件文档，支持在线预览和下载。
            </Text>
            {article.attachments.map(attachment => (
              <PdfViewer 
                key={attachment.id}
                attachment={{
                  ...attachment,
                  pdf_url: attachment.pdf_url,
                  pdf_status: attachment.pdf_status || (attachment.pdf_url ? 'completed' : 'unknown'),
                  // 确保PDF状态正确传递
                  pdfStatus: attachment.pdf_status || attachment.pdfStatus || (attachment.pdf_url ? 'completed' : 'unknown')
                }}
                showActions={true}
              />
            ))}
          </div>
        )}

        <Divider />

        {/* 作品统计 */}
        <Row justify="center">
          <Col>
            <Space size="large">
              <Space>
                <EyeOutlined />
                <Text>{article.view_count || 0} 浏览</Text>
              </Space>
            </Space>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default ArticleDetail;